import gzip
import os.path
import re
from rich.console import Console
from rich import print

from config import get_config
from decorator import format_print, sendemail
from .log_file import get_log_files
from .match_read import get_match_read
from .LogFile import LogFile


# @sendemail
@format_print
def log_read():
    files = get_log_files()
    match_list = get_match_read()

    reg_list = [re.compile(rf'{i}') for i in match_list]

    result = []

    for file in files:
        match = singlefile_match(file, reg_list)

        result.append({
            "file": os.path.basename(file),
            "file_path": file,
            "match": match
        })
        print(f"[green]{os.path.basename(file)} 解析完成[/green]")

    return result
    # f


# 进行单个文件匹配查询
def singlefile_match(file_path, reg_list):
    conf = get_config()
    config = dict(conf)
    math_list = []

    try:
        with LogFile(file_path) as file:
            while True:
                line = file.readline().decode('utf-8')
                if not line:
                    break
                math_reg = [reg for reg in reg_list if reg.search(line)]
                # print(math_reg)
                if math_reg is not None and len(math_reg) > 0:
                    match_lines = config.get('match_lines', 1)
                    if match_lines == 1:
                        match_result = config.get('match_result', 'line')
                        target = line if match_result == 'line' else math_reg[0].search(line).group()
                        math_list.append({
                            "reg": math_reg[0].pattern,
                            "target": target
                        })
                    else:
                        target = lines_result(file, line, match_lines)
                        math_list.append({
                            "reg": math_reg[0].pattern,
                            "target": target
                        })

    except Exception as e:
        print(e)
        raise Exception

    return math_list





def lines_result(file: LogFile, match_start_line: str, match_lines: int) -> str:
    all_lines = match_start_line
    for i in range(1, match_lines):
        line = file.readline()
        if not line:
            break
        all_lines = all_lines + line.decode('utf-8')

    return all_lines
